import 'dart:convert';
import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'package:flui/flui.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:fzcgx_app/common/adapter_utils.dart';
import 'package:fzcgx_app/common/color_utils.dart';
import 'package:fzcgx_app/network/http.dart';
import 'package:fzcgx_app/network/urls.dart';
import 'package:fzcgx_app/ui/base/base_view_model.dart';
import 'package:fzcgx_app/ui/order/model/order_colour_model.dart';
import 'package:fzcgx_app/ui/order/model/order_size_model.dart';
import 'package:image_picker/image_picker.dart';
import 'package:nav_router/nav_router.dart';

class OrderAddViewModel extends BaseViewModel {
  List productPictures;
  List<OrderColourModel> selectOrderColourModels;
  List<OrderSizeModel> selectOrderSizeModels;
  final picker = ImagePicker();
  String contractPicture = '';
  TextEditingController coloureController = TextEditingController();
  TextEditingController sizeController = TextEditingController();
  TextEditingController robTypeController = TextEditingController();
  int robType = 0;
  TextEditingController endTimeController = TextEditingController();

  TextEditingController earnestController = TextEditingController();

  TextEditingController proNameController = TextEditingController();

  TextEditingController proStyleController = TextEditingController();

  TextEditingController styleNoController = TextEditingController();

  TextEditingController priceController = TextEditingController();

  TextEditingController craftController = TextEditingController();

  TextEditingController numController = TextEditingController();

  OrderAddViewModel() {
    this.productPictures = List();
    this.selectOrderColourModels = List<OrderColourModel>();
    this.selectOrderSizeModels = List<OrderSizeModel>();
  }
  void setOrderColourModel(List<OrderColourModel> models) {
    this.selectOrderColourModels = models;
    String str = '';
    this.selectOrderColourModels.forEach((element) {
      str += element.name + ' ';
    });
    coloureController.text = str;
    notifyListeners();
  }

  void setOrderSizeModel(List<OrderSizeModel> models) {
    this.selectOrderSizeModels = models;
    String str = '';
    this.selectOrderSizeModels.forEach((element) {
      str += element.name + ' ';
    });
    sizeController.text = str;
    notifyListeners();
  }

  void selectPhoto(BuildContext context, int photoType) async {
    int result = await showModalBottomSheet(
      isScrollControlled: true,
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadiusDirectional.only(
          topStart: Radius.circular(10),
          topEnd: Radius.circular(10),
        ),
      ),
      builder: (BuildContext context) {
        return StatefulBuilder(builder: (context1, state) {
          return IntrinsicWidth(
              stepHeight: 1.0,
              child: SingleChildScrollView(
                child: Container(
                  padding: EdgeInsets.only(
                      bottom: MediaQuery.of(context).viewInsets.bottom),
                  child: Column(
                    children: [
                      Container(
                        color: Color.fromRGBO(240, 240, 248, 1),
                        height: 60,
                        padding: EdgeInsets.symmetric(
                            horizontal: AdapterUtils.getWidth(12)),
                        child: Row(
                          children: <Widget>[
                            Text(
                              '提示',
                              style: TextStyle(
                                  fontSize: AdapterUtils.getSp(16),
                                  color: ColorUtils.defaultColor,
                                  fontWeight: FontWeight.w500),
                            ),
                            Spacer(),
                            InkWell(
                              onTap: () {
                                pop();
                              },
                              child: Icon(Icons.close,
                                  color: ColorUtils.text2Color),
                            )
                          ],
                        ),
                      ),
                      InkWell(
                        onTap: () => Navigator.pop(context, 1),
                        child: Container(
                          color: Colors.white,
                          child: ListTile(
                            title: Text(
                              '从相册选择',
                              style: TextStyle(
                                  fontSize: AdapterUtils.getSp(14),
                                  color: ColorUtils.text1Color,
                                  fontWeight: FontWeight.w400),
                            ),
                          ),
                        ),
                      ),
                      InkWell(
                        onTap: () => Navigator.pop(context, 2),
                        child: Container(
                          color: Colors.white,
                          child: ListTile(
                            title: Text(
                              '拍照',
                              style: TextStyle(
                                  fontSize: AdapterUtils.getSp(14),
                                  color: ColorUtils.text1Color,
                                  fontWeight: FontWeight.w400),
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ));
        });
      },
    );
    if (result == null) {
      return;
    }
    if (result == 1) {
      getImage(1, photoType);
    } else {
      getImage(2, photoType);
    }
  }

  Future<Null> getImage(int source, int photoType) async {
    final selectedFile = await picker.getImage(
        source: source == 1 ? ImageSource.gallery : ImageSource.camera);
    if (selectedFile != null) {
      String path = selectedFile.path;
      var name = path.substring(path.lastIndexOf("/") + 1, path.length);
      //var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
      FormData formData = new FormData.fromMap({
        "name": "file",
        'enctype': "multipart/form-data",
        "img": await MultipartFile.fromFile(path, filename: name),
      });

      Dio dio = new Dio();
      dio.interceptors
          .add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
        dio.lock();

        var authorization = SpUtil.getString('token');
        options.headers["token"] = authorization;

        dio.unlock();
        return options;
      }));
      var dismiss = FLToast.showLoading(text: '正在上传');
      var respone = await dio.post<String>(
        Urls.base_url + Urls.upload_photo,
        data: formData,
      );
      dismiss();
      if (respone.statusCode == 200) {
        Map imgData = jsonDecode(respone.data);
        print('uu:$imgData');
        if (photoType == 1) {
          this.productPictures.add(imgData['data']['img']['img'].toString());
        } else if (photoType == 2) {
          this.contractPicture = imgData['data']['img']['img'].toString();
        }

        notifyListeners();
      }
    }
  }

  void delProductPictures(BuildContext context, String url) {
    showDialog(
        context: context,
        builder: (context) {
          return Material(
            type: MaterialType.transparency,
            child: Center(
                child: Container(
              height: 128,
              width: 280,
              color: Colors.white,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  SizedBox(
                    height: 35,
                  ),
                  Align(
                    child: Text('您确定删除此图片吗？',
                        style: TextStyle(
                            color: Color(0xff141F33),
                            fontWeight: FontWeight.w400,
                            fontSize: AdapterUtils.getSp(16))),
                    alignment: Alignment.center,
                  ),
                  SizedBox(
                    height: 27,
                  ),
                  Container(
                    height: 1,
                    color: Color(0xff191F25).withOpacity(0.08),
                  ),
                  Container(
                    height: 40,
                    child: Row(
                      children: <Widget>[
                        Expanded(
                            child: InkWell(
                          onTap: () {
                            Navigator.pop(context, 0);
                          },
                          child: Container(
                            alignment: Alignment.center,
                            child: Text('取消',
                                style: TextStyle(
                                    color: Color(0xff99A2AD),
                                    fontWeight: FontWeight.w500,
                                    fontSize: AdapterUtils.getSp(17))),
                          ),
                        )),
                        Container(
                          width: 1,
                          color: Color(0xff191F25).withOpacity(0.08),
                        ),
                        Expanded(
                            child: InkWell(
                          onTap: () {
                            Navigator.pop(context, 1);
                          },
                          child: Container(
                            alignment: Alignment.center,
                            child: Text('确认',
                                style: TextStyle(
                                    color: Color(0xffFF3D3E),
                                    fontWeight: FontWeight.w500,
                                    fontSize: AdapterUtils.getSp(17))),
                          ),
                        ))
                      ],
                    ),
                  )
                ],
              ),
            )),
          );
        }).then((value) {
      if (value == 1) {
        this.productPictures.remove(url);
        notifyListeners();
      }
    });
  }

  void delContractPicture(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          return Material(
            type: MaterialType.transparency,
            child: Center(
                child: Container(
              height: 128,
              width: 280,
              color: Colors.white,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  SizedBox(
                    height: 35,
                  ),
                  Align(
                    child: Text('您确定删除此图片吗？',
                        style: TextStyle(
                            color: Color(0xff141F33),
                            fontWeight: FontWeight.w400,
                            fontSize: AdapterUtils.getSp(16))),
                    alignment: Alignment.center,
                  ),
                  SizedBox(
                    height: 27,
                  ),
                  Container(
                    height: 1,
                    color: Color(0xff191F25).withOpacity(0.08),
                  ),
                  Container(
                    height: 40,
                    child: Row(
                      children: <Widget>[
                        Expanded(
                            child: InkWell(
                          onTap: () {
                            Navigator.pop(context, 0);
                          },
                          child: Container(
                            alignment: Alignment.center,
                            child: Text('取消',
                                style: TextStyle(
                                    color: Color(0xff99A2AD),
                                    fontWeight: FontWeight.w500,
                                    fontSize: AdapterUtils.getSp(17))),
                          ),
                        )),
                        Container(
                          width: 1,
                          color: Color(0xff191F25).withOpacity(0.08),
                        ),
                        Expanded(
                            child: InkWell(
                          onTap: () {
                            Navigator.pop(context, 1);
                          },
                          child: Container(
                            alignment: Alignment.center,
                            child: Text('确认',
                                style: TextStyle(
                                    color: Color(0xffFF3D3E),
                                    fontWeight: FontWeight.w500,
                                    fontSize: AdapterUtils.getSp(17))),
                          ),
                        ))
                      ],
                    ),
                  )
                ],
              ),
            )),
          );
        }).then((value) {
      if (value == 1) {
        this.contractPicture = '';
        notifyListeners();
      }
    });
  }

  void bindRobType(BuildContext context) {
    showFLBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return FLCupertinoActionSheet(
            backgroundColor: Colors.white,
            child: Container(
              padding: const EdgeInsets.symmetric(),
              child: Column(
                children: <Widget>[
                  SizedBox(height: AdapterUtils.getHeight(11)),
                  Text(
                    '选择抢单类型',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontSize: AdapterUtils.getSp(14),
                      color: Color(0xff999999),
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                  SizedBox(height: AdapterUtils.getHeight(11)),
                  Divider(),
                  InkWell(
                      onTap: () {
                        Navigator.pop(context, 1);
                      },
                      child: Container(
                        height: AdapterUtils.getHeight(50),
                        alignment: Alignment.center,
                        child: Text(
                          '抢单',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: AdapterUtils.getSp(16),
                            color: Color(0xff141F33),
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      )),
                  Divider(),
                  InkWell(
                      onTap: () {
                        Navigator.pop(context, 2);
                      },
                      child: Container(
                        height: AdapterUtils.getHeight(50),
                        alignment: Alignment.center,
                        child: Text(
                          '普通单',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: AdapterUtils.getSp(16),
                            color: Color(0xff141F33),
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      )),
                  SizedBox(height: AdapterUtils.getHeight(13)),
                ],
              ),
            ),
            cancelButton: CupertinoActionSheetAction(
              child: Text(
                '取消',
                style: TextStyle(
                  fontSize: AdapterUtils.getSp(16),
                  color: Color(0xff141F33),
                  fontWeight: FontWeight.w400,
                ),
              ),
              isDefaultAction: true,
              onPressed: () {
                Navigator.pop(context, 0);
              },
            ),
          );
        }).then((value) {
      if (value != null) {
        this.robType = value;
        robTypeController.text = this.robType == 0
            ? ''
            : this.robType == 1 ? '抢单' : this.robType == 2 ? '普通单' : '';
        notifyListeners();
      }
    });
  }

  void showDate(BuildContext context) {
    DatePicker.showDateTimePicker(context,
        showTitleActions: true,
        minTime: DateTime.now(),
        maxTime: DateTime(2050, 12, 31), onChanged: (date) {
      print('change $date');
    }, onConfirm: (date) {
      print('confirm $date');
      this.endTimeController.text = formatDate(date, [
        yyyy,
        "-",
        mm,
        "-",
        dd,
        " ",
        " ",
        HH,
        ":",
        nn,
      ]);
      notifyListeners();
    }, currentTime: DateTime.now(), locale: LocaleType.zh);
  }

  void postApi() {
   
    if (this.robType == 0) {
      FLToast.showText(text: '请选择抢单类型');
      return;
    }
    if (this.robType == 1 && this.earnestController.text.isEmpty) {
      FLToast.showText(text: '请输入抢单保证金');
      return;
    }
    if(this.proNameController.text.isEmpty){
 FLToast.showText(text: '请输入产品名称');
      return;
    }
    if(this.proStyleController.text.isEmpty){
 FLToast.showText(text: '请输入款式名称');
      return;
    }
    if(this.styleNoController.text.isEmpty){
 FLToast.showText(text: '请输入款号');
      return;
    }
    if(this.selectOrderColourModels.length==0){
FLToast.showText(text: '请选择款式颜色');
      return;
    }
    if(this.selectOrderSizeModels.length==0){
FLToast.showText(text: '请选择尺码');
      return;
    }
    if(this.priceController.text.isEmpty){
 FLToast.showText(text: '请输入单价（元）');
      return;
    }
    if(this.numController.text.isEmpty){
 FLToast.showText(text: '请输入数量（件）');
      return;
    }
    if(this.endTimeController.text.isEmpty){
 FLToast.showText(text: '请选择抢单截止时间');
      return;
    }
     if(this.craftController.text.isEmpty){
 FLToast.showText(text: '请输入工艺要求');
      return;
    }
    if(this.productPictures.length==0){
 FLToast.showText(text: '请上传产品图片');
      return;
    }
    if(this.contractPicture.isEmpty){
 FLToast.showText(text: '请上传合同');
      return;
    }
    var dismiss = FLToast.loading(text: '正在发布...');
    Http.instance.post(
        'home/bale-pub-info',
        {
          'robType': this.robType,
          'proStyle':this.proStyleController.text,
          'proName':this.proNameController.text,
          'styleNo':this.styleNoController.text,
          'num':this.numController.text,
          'price':this.priceController.text,
          'endTime':this.endTimeController.text,
          'earnest':this.earnestController.text,
          'craft':this.craftController.text,
          'imgs':jsonEncode(this.productPictures),
          'colors': this.getSlectColorsStr(),
          'sizes':this.getSlectSizesStr(),
          'contract':this.contractPicture,
        },
        onSuccess: (data) {
          FLToast.showSuccess(text: '发布成功');
          pop();
        },
        onError: (error) {},
        onFail: (fail) {},
        complete: () {
          dismiss();
        });
  }
 String getSlectColorsStr(){
   List lists=List();
   this.selectOrderColourModels.forEach((element) {
     lists.add(element.id);
   });
   return jsonEncode(lists);
  }
  String getSlectSizesStr(){
   List lists=List();
   this.selectOrderSizeModels.forEach((element) {
     lists.add(element.id);
   });
   return jsonEncode(lists);
  }
}
